package com.yjha.lzmarathonsys.consumer;

import com.rabbitmq.client.Channel;
import com.yjha.lzmarathonsys.bean.TbComment;
import com.yjha.lzmarathonsys.config.RabbitmqConfig;
import com.yjha.lzmarathonsys.mapper.TbCommentMapper;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Date;

@Component
public class CommentConsumer {

    @Autowired
    private TbCommentMapper commentMapper;

    @RabbitListener(queues = RabbitmqConfig.QUEUE_COMMENT)
    public void processLikeMessage(TbComment comment, Channel channel, Message message) throws IOException {
        try {
            comment.setTbCreateTime(new Date());
            comment.setTbUpdateTime(new Date());
            comment.setTbTargetStatus(0);

            commentMapper.insert(comment);

            // 处理rootId
            if (comment.getTbParentId() == 0) {
                comment.setTbRootId(comment.getTbCommentId());
            } else {
                TbComment parent = commentMapper.selectById(comment.getTbParentId());
                comment.setTbRootId(parent != null ? parent.getTbRootId() : (int) 0L);
            }

            commentMapper.updateById(comment);

            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
        }
    }
}
